package com.mes.web.controller.tdd;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.gson.Gson;
import com.mes.entity.tdd.Staff;
import com.mes.entity.tdd.Supplier;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.tdd.SupplierService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;
/**
 * 
 * @ClassName:SupplierController
 * @Description:供应商
 * @Author tdd
 * @Date 2018年3月22日下午3:44:34
 * @version 1.0
 */
@Controller
@RequestMapping("/supplier")
public class SupplierController {
	//引入供应商的service
	@Resource public SupplierService supplierService;
	/**
	 *供应商 页列表查询
	 * @param pageBean 分页+条件
	 * @param limit 每页条数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/list")
	public void materieDemandList(Tpage pageBean,HttpServletRequest request,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		
		/*String suppliername = request.getParameter("suppliername"); 
		if(null != suppliername && !suppliername.equals("")){
			suppliername = new String(suppliername.getBytes("iso8859-1"),"utf-8");
			pageBean.setSuppliername(suppliername);
		}
		
		String sutype = request.getParameter("sutype"); 
		if(null != sutype && !sutype.equals("")){
			sutype = new String(sutype.getBytes("iso8859-1"),"utf-8");
			pageBean.setSutype(sutype);
		}*/
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		//分页列表查询
		List<Supplier> suppliers=supplierService.list(pageBean);
		//总条数
		int total=supplierService.total(pageBean);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(suppliers, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 查询所有供应商
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/all")
	public void all(HttpServletResponse response) throws Exception{
		Tpage pageBean= new Tpage();
		//未删除
		pageBean.setIsdelete("0");
		List<Supplier> list=supplierService.all(pageBean);
		Gson gson = new Gson();
		ResponseUtil.write(response, gson.toJson(list));
	}
	/**
	 * 添加
	 * @param response response对象
	 * @param supplier 供应商
	 * @param request request对象
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/add")
	public void add(HttpServletResponse response,Supplier supplier,HttpServletRequest request) throws IOException{
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        //根据编号查所有
        Tpage pageBean = new Tpage();
        pageBean.setSuppliernumbering(supplier.getSuppliernumbering());
        pageBean.setIsdelete("0");
        List<Supplier> total = supplierService.all(pageBean);
    	//判断编号是否重复
		//编号重复
		if (total.size()>0) {
			response.getWriter().print("-1");
		//编号不重复
		}else{
        	//添加库区
        	//录入人
        	supplier.setSuenter(userSession.getStaffname());
        	//录入时间
			supplier.setSuentertime(date);
        	//是否删除标识，未删除
			supplier.setIsdelete("0");
        	//添加
        	Long id = supplierService.add(supplier);
        	//添加成功
        	if (null != id && id >= 1) {
        		response.getWriter().print("1");
        		//未成功
        	} else {
        		response.getWriter().print("0");
        	}
		}
	}
	/**
	 * 到修改
	 * @param request request对象
	 * @param response response对象
	 * @return null
	 * @throws Exception 异常
	 */
	@RequestMapping("/toupdate")
	public String toupdata(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//json
		Gson gson=new Gson();
		//根据id查询数据
		Tpage pageBean = new Tpage();
		//获取id
		pageBean.setSupplierid(Long.valueOf((Integer.parseInt(request.getParameter("supplierid")))));
		//未删除
		pageBean.setIsdelete("0");
		List<Supplier> list = supplierService.all(pageBean);
		//获得数据
		if (list.size()>0) {
			//传递数据到页面
			ResponseUtil.write(response, gson.toJson(list.get(0)));
		}
		//跳转到修改页面
		return null;
	}
	/**
	 * 修改
	 * @param supplier 供应商
	 * @param response response对象
	 * @param request request对象
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/update")
	public void updata(Supplier supplier,HttpServletResponse response,HttpServletRequest request) throws IOException{
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
		//修改
        //录入人
    	supplier.setSuenter(userSession.getStaffname());
    	//录入时间
        supplier.setSuentertime(date);
    	//是否删除标识，未删除
        supplier.setIsdelete("0");
		
		//根据id查数据
        //修改前数据
    	Tpage pageBean = new Tpage();
		//获取id
		pageBean.setSupplierid(supplier.getSupplierid());
		//未删除
		pageBean.setIsdelete("0");
		List<Supplier> list = supplierService.list(pageBean);
		//如果有该条数据
		if (list.size()>0) {
			//编号是否重复标识
			  //根据编号查所有库区
	        Tpage page = new Tpage();
	        page.setIsdelete("0");
	        page.setSuppliernumbering(supplier.getSuppliernumbering());
			List<Supplier> suppliers = supplierService.all(page);
	    	//判断编号是否重复
			int num = 0;
			//编号重复
	        for (int i = 0; i < suppliers.size(); i++) {
	        	//判断编号是否重复
				if (supplier.getSuppliernumbering().equals(suppliers.get(i).getSuppliernumbering()) && !list.get(0).getSuppliernumbering().equals(suppliers.get(i).getSuppliernumbering())) {
					num++;
				}
			}
	      //编号不重复
	        if (num <= 0) {
	        	//修改
				int n = supplierService.updata(supplier);
				//修改成功
				if (n >= 1) {
					response.getWriter().print("1");
					//未成功
				} else {
					response.getWriter().print("0");
				}
			}else {
				//编号重复
				response.getWriter().print("-1");
			}
		//如果没有该条数据(没有)
		}else {
			//该数据不存在
			response.getWriter().print("2");
		}
	}
	/**
	 * 删除 
	 * @param ids 供应商id用","连接而成的字符串
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//判断session
        /*HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");*/
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        List<Long> listId = StringUtil.splitListL(ids, ",");
        for (int i = 0; i < listId.size(); i++) {
        	//根据id查数据
        	//修改前数据
        	Tpage pageBean = new Tpage();
        	//获取id
        	pageBean.setSupplierid(listId.get(i));
        	//未删除
        	pageBean.setIsdelete("0");
        	List<Supplier> list = supplierService.all(pageBean);
        	//如果有该条数据
        	if (list.size()>0) {
        		Supplier supplier = list.get(0);
        		/* //录入人
		    	supplier.setSuenter(userSession.getStaffname());*/
		    	//录入时间
        		supplier.setSuentertime(date);
        		//是否删除指定删除
        		supplier.setIsdelete("1");
        		//删除（假删除）
        		int n = supplierService.updatadelete(supplier);
        		//删除成功
        		if (n >= 1) {
        			//未成功
        		} else {
        			response.getWriter().print("0");
        		}
        		//如果没有该条数据(没有)
        	}else {
        		//该数据不存在
        		response.getWriter().print("2");
        	}
		}
        response.getWriter().print("1");
	}	
		
	
	
	
	/**
	 * 导出模板
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ExcelUtils.exportFile("供应商导入模板",names(), response);
	}	
	
	/**
	 * 导出当前页数据
	 * @param pageBean 分页+条件
	 * @param limit 每页条数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExport")
	public void doExport(Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<Supplier> suppliers=supplierService.list(pageBean);
		List<List<String>> lists = supplierzhuanlist(suppliers);
		ExcelUtils.export("供应商当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param pageBean 分页+条数
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExportall")
	public void doExportall(Tpage pageBean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//未删除
		pageBean.setIsdelete("0");
		List<Supplier> suppliers=supplierService.all(pageBean);
		List<List<String>> lists = supplierzhuanlist(suppliers);
		ExcelUtils.export("供应商所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file 导入的Excel文件
	 * @param request request对象
	 * @param response response对象
	 * @throws URISyntaxException 检查异常抛出以指示字符串无法解析为URI引用。
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = ((HttpSession) request).getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       String xls = "xls";
	       String xlsx = "xlsx";
	       if(xls.equals(subfix)){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(xlsx.equals(subfix)){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       /*HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");*/
	       String staffname = null;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	       String   date   =   sDateFormat.format(new Date());
	       
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    
	    	   Supplier supplier = new Supplier();
	    	   supplier.setSuppliernumbering(list.get(0));
	    	   supplier.setSuppliername(list.get(1));
	    	   supplier.setCapital(list.get(2));
	    	   supplier.setSutype(list.get(3));
	    	   supplier.setOrderingcycle(list.get(4));
	    	   supplier.setTermspayment(list.get(5));
	    	   supplier.setPaymentperiod(list.get(6));
	    	   supplier.setLegalrepresentative(list.get(7));
	    	   supplier.setBusinesslicense(list.get(8));
	    	   supplier.setHome(list.get(9));
	    	   supplier.setOperate(list.get(10));
	    	   supplier.setAddress(list.get(11));
	    	   supplier.setContact(list.get(12));
	    	   supplier.setContactphone(list.get(13));
	    	   supplier.setMail(list.get(14));
	    	   
	    	   int ff = addSupplier(supplier, request, date, staffname);
	    	   supplier = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return 导出模板的表头集合
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("供应商编号");
		list.add("企业名称");
		list.add("注册资本");
		list.add("类型");
		list.add("订货周期");
		list.add("付款方式");
		list.add("付款周期");
		list.add("法人代表名称");
		list.add("营业执照注册号");
		list.add("所在地");
		list.add("经营类别");
		list.add("详细地址");
		list.add("联系人");
		list.add("联系电话");
		list.add("邮箱");
		return list;
	}
	/**
	 * 导出数据表头
	 * @return 导出数据表头集合
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("供应商编号");
		list.add("企业名称");
		list.add("注册资本");
		list.add("类型");
		list.add("订货周期");
		list.add("付款方式");
		list.add("付款周期");
		list.add("法人代表名称");
		list.add("营业执照注册号");
		list.add("所在地");
		list.add("经营类别");
		list.add("详细地址");
		list.add("联系人");
		list.add("联系电话");
		list.add("邮箱");
		list.add("录入人");
		list.add("录入时间");
		return list;
	}
	/**
	 * 根据导出数据表头把List<Supplier>转List<List<String>>
	 * @param suppliers 供应商集合
	 * @return 字符串双集合
	 */
	public List<List<String>> supplierzhuanlist (List<Supplier> suppliers){
		List<List<String>> lists = new ArrayList<>();
		for (Supplier supplier : suppliers) {
			List<String> list = new ArrayList<>();
			list.add(supplier.getSuppliernumbering());
			list.add(supplier.getSuppliername());
			list.add(supplier.getCapital());
			list.add(supplier.getSutype());
			list.add(supplier.getOrderingcycle());
			list.add(supplier.getTermspayment());
			list.add(supplier.getPaymentperiod());
			list.add(supplier.getLegalrepresentative());
			list.add(supplier.getBusinesslicense());
			list.add(supplier.getHome());
			list.add(supplier.getOperate());
			list.add(supplier.getAddress());
			list.add(supplier.getContact());
			list.add(supplier.getContactphone());
			list.add(supplier.getMail());
			list.add(supplier.getSuenter());
			list.add(supplier.getSuentertime());
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param supplier 供应商
	 * @param request request对象
	 * @param date 当前数据
	 * @param staffname 录入人
	 * @return 添加是否采购标识
	 */
	public int addSupplier(Supplier supplier,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
        
		//根据编号查所有
        Tpage pageBean = new Tpage();
        pageBean.setSuppliernumbering(supplier.getSuppliernumbering());
        pageBean.setIsdelete("0");
        List<Supplier> total = supplierService.all(pageBean);
    	//判断编号是否重复
		//编号重复
		if (total.size()>0) {
			flag = 1;
		//编号不重复
		}else{
			//添加库区
        	//录入人
        	/*supplier.setSuenter(userSession.getStaffname());*/
        	//录入时间
			supplier.setSuentertime(date);
        	//是否删除标识，未删除
			supplier.setIsdelete("0");
        	//添加
        	Long id = supplierService.add(supplier);
        	//添加成功
        	if (null != id && id >= 1) {
        		flag = 1;
        		//未成功
        	} else {
        		flag = 0;
        	}
		}
		return flag;
	}
}
